package com.zsy.service.impl;

import com.zsy.entity.*;
import com.zsy.mapper.IContractMapper;
import com.zsy.service.IContractService;
import com.zsy.utils.Result;
//import com.zsy.utils.ThreadLocalUtil;
import com.zsy.vo.UserVO;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class ContractServiceImpl implements IContractService {
    @Autowired
    private IContractMapper conmap;

    @Override
    public Result addContract(ContractUser contract) {
//        Map<String,Object> map = ThreadLocalUtil.get();
//        String dp = (String) map.get("department");
//        String PersonInCharge = (String) map.get("username");
//        if(dp.equals("销售部") || dp.equals("管理员")){
        //拿用户名
        //获取用户主体信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //获取用户身份信息
        User principal = (User) authentication.getPrincipal();
        System.out.println(principal.getUsername());
        int i = -1;
            System.out.println(contract);
            ContractUser contractUser = conmap.selectPersonInCharge(contract.getContractNumber());
            contract.setPersonInCharge(principal.getUsername());
            if (contractUser == null && contract.getContractName() != null){
                i = conmap.addContract(contract);
                if(i > -1){
                    return Result.ok("添加成功");
                }else {
                    return Result.error("添加失败");
                }
            }else {
                return Result.error("数据已存在");
            }
//        }
//        else {
//            return Result.error("你没有权限添加");
//        }
    }

    @Override
    public Result selectContractAll() {
//        Map<String,Object> map = ThreadLocalUtil.get();
//        String department = (String) map.get("department");
//        String PersonInCharge = (String) map.get("username");

//        if(department.equals("销售部") || department.equals("管理员")){
//            System.out.println("负责人"+PersonInCharge);

            List<ContractUser> contractUsers = conmap.selectContractAll();
            List<ContractUser> contractUsers1 = new ArrayList<>();
            if(contractUsers != null){
                for (ContractUser contractUser:contractUsers) {
                    if(contractUser.getDelStatus() == 1){
                        contractUsers1.add(contractUser);
                    }
                }
                return Result.ok(contractUsers1);
            }else {
                return Result.error("未获取到数据");
            }
//        }
//        else {
//            return Result.error("你不是销售部，权限不足");
//        }
    }

    @Override
    public Result getClientUserName() {
        List<String> clientUserName = conmap.getClientUserName();
        System.out.println(clientUserName);
        if(clientUserName != null){
            return Result.ok(clientUserName);
        }
        return Result.error("未获取到数据");
    }

    //查询合同数量,金额,名称
    @Override
    public Result getCount() {
        ContractCount num = conmap.getNum();
        List<ContractCount> price = conmap.getPrice();
        List<ContractUser> countCt = conmap.getCountCt();
        int priceCount = 0;
        List<String> ContractName = new ArrayList<>();
        for (ContractCount item:price) {
            System.out.println(item.getCountPrice());
            priceCount += item.getCountPrice();
        }
        for (ContractUser item:countCt) {
            ContractName.add(item.getContractName());
        }
        Map<String,Object> rest = new HashMap<>();
        rest.put("numAll:",num.getCountNum());
        rest.put("priceAll",priceCount);
        rest.put("ContractName",ContractName);
        System.out.println(rest);

        return Result.ok(rest);
    }

    //分页查询合同记录
    @Override
    public Result getLimit(int pagee,int index) {
        int page = (pagee - 1) * index;
        List<ContractUser> limit = conmap.getLimit(page, index);
        if(pagee > -1 && index > -1 ){
            if(limit != null && !limit.isEmpty()){
                return Result.ok(limit);
            }else {
                return Result.error("无数据");
            }
        }else {
            return Result.error("未获取到页码与条数");
        }
    }
    //批量删除
    public Result delListContract(Integer[] ids){
        int i = conmap.delListContract(ids);
        if(i > 0){
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }

    @Override
    public Result getFile() {
        List<FileStore> file = conmap.getFile();
        List<String> imageTypes = Arrays.asList("image/jpeg","image/png","image/gif","image/bmp","image/webp","image/svg+xml","image/x-icon");
        List<FileStore> fileData = new ArrayList<>();
        for (FileStore fileStore:file) {
            if(!imageTypes.contains(fileStore.getContentType())){
                fileData.add(fileStore);
            }
        }
        System.out.println(fileData);
        if(fileData != null){
            return Result.ok(fileData);
        }else {
            return Result.error("未获取到数据");
        }

    }

    @Override
    public Result getIco() {
//        Map<String,Object> mp = ThreadLocalUtil.get();
//        String username = (String) mp.get("username");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User principal = (User) authentication.getPrincipal();

        Ico ico = conmap.getIco(principal.getUsername());
        //把数据库内的blob对象赋值给byte[]
        byte[] fileData = ico.getFileData();
        //把byte[]字节符组转换未base54编码的字符串
        String newData = Base64.getEncoder().encodeToString(fileData);
//        String newData = new String(fileData, StandardCharsets.UTF_8);
        //拼接为可以直接显示图片的字符串
        String newIco = "data:"+ico.getContentType()+";base64,"+newData;
        System.out.println(newIco);
        if(ico != null){
            return Result.ok(newIco);
        }else {
            return Result.error("未拿到头像");
        }
    }

    @Override
    public Result getUsers() {
//        Map<String,Object> mp = ThreadLocalUtil.get();
//        String username = (String) mp.get("username");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User principal = (User) authentication.getPrincipal();
        User users = conmap.getUsers(principal.getUsername());
        System.out.println(users);
        if(users != null){
            return Result.ok(users);
        }
        return Result.error("错误");
    }

    @Override
    public Result updateUser(User user) {
        if(user != null){
            int i = conmap.updateUser(user);
            if(i > -1){
                return Result.ok("修改成功");
            }else {
                return Result.error("修改失败");
            }
        }
        return Result.error("未获取到数据");
    }
    @Override
    public Result updatePwd(String password,String lowPassword) {
        if(password != null && lowPassword != null){
//            Map<String,Object> mp = ThreadLocalUtil.get();
//            String username = (String) mp.get("username");
//            String phone = (String) mp.get("phone");
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User principal = (User) authentication.getPrincipal();
            User users = conmap.getUsers(principal.getUsername());
            if(users.getPassword().equals(lowPassword)){
                int i = conmap.updatePwd(password, principal.getPhone());
                if(i > -1){
                    return Result.ok("密码修改成功");
                }else {
                    return Result.error("密码修改失败");
                }
            }

        }
        return Result.error("未获取密码");
    }

    @Override
    public Result fileupload(MultipartFile uploadfile) {
        List<String> imageTypes = Arrays.asList("image/jpeg","image/png","image/gif","image/bmp","image/webp","image/svg+xml","image/x-icon");
        System.out.println(uploadfile);
        System.out.println("------fileupload"+uploadfile.getName());
        System.out.println(uploadfile.getSize());
        //文件大小
        Integer filesize = (int) uploadfile.getSize();
        //获取文件名
        String filename = uploadfile.getOriginalFilename();
        //存在服务器上名称修改
//        filename = UUID.randomUUID()+filename;
        filename = "上传："+filename;
//        Map<String,Object> mp = ThreadLocalUtil.get();
//        String username = (String) mp.get("username");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User principal = (User) authentication.getPrincipal();
//        数据库里存一份，本地存一份，
        try {
            FileStore fileStore = new FileStore();
            fileStore.setFileName(filename);
            fileStore.setFileSize(filesize);
            fileStore.setContentType(uploadfile.getContentType());
            fileStore.setFileData(uploadfile.getBytes());
            System.out.println(fileStore);
            conmap.fileupload(fileStore);
            if(imageTypes.contains(uploadfile.getContentType())){
                int i = conmap.updateUserIco(principal.getUsername(), filename);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //定义服务器上的存储路径
        String dirPath = "D:/file/";
        File filePath = new File(dirPath);
        //如果路径不存在，就传教
        if(!filePath.exists()){
            filePath.mkdir();
        }
        try {
            //文件上传
            uploadfile.transferTo(new File(dirPath+filename));
        }catch (IOException e){
            e.printStackTrace();
            return Result.error("上传失败");
        }
        return Result.ok("上传成功");
    }

    @Override
    public ResponseEntity<byte[]> fileDownload(String filename) {
        System.out.println(filename);
        //指定文件下载地址的目录
        String dirPath = "D:/file/";
        File file = new File(dirPath+filename);
        System.out.println(file);
        HttpHeaders headers = new HttpHeaders();
        //告诉浏览器，打开方式（附件）
        headers.setContentDispositionFormData("attachment",filename);
        //以二进制字节流的方式下载
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try{
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        }catch (IOException e){
            e.printStackTrace();
            return new ResponseEntity<>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
        }
    }

}
